package com.fzfnn.scrapbook.mapper;

import com.fzfnn.scrapbook.entity.Message;
import com.fzfnn.scrapbook.vo.PrivateChatUserDTO;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface MessageMapper {
    @Insert("INSERT INTO message (sender_id, receiver_id, content, send_time) VALUES (#{senderId}, #{receiverId}, #{content}, NOW())")
    void saveMessage(Message message);

    @Select("SELECT * FROM message WHERE (sender_id = #{userId1} AND receiver_id = #{userId2}) OR (sender_id = #{userId2} AND receiver_id = #{userId1}) ORDER BY send_time")
    List<Message> getChatHistory(@Param("userId1") int userId1, @Param("userId2") int userId2);

    // 查询与我私聊过的所有用户的最新一条消息
    @Select("SELECT \n" +
            "            IF(m.sender_id = #{userId}, m.receiver_id, m.sender_id) AS userId,\n" +
            "            u.username,\n" +
            "            m.content AS lastMessage,\n" +
            "            m.send_time AS lastTime\n" +
            "        FROM message m\n" +
            "        JOIN (\n" +
            "            SELECT \n" +
            "                IF(sender_id = #{userId}, receiver_id, sender_id) AS userId,\n" +
            "                MAX(send_time) AS maxTime\n" +
            "            FROM message\n" +
            "            WHERE sender_id = #{userId} OR receiver_id = #{userId}\n" +
            "            GROUP BY userId\n" +
            "        ) t ON ((m.sender_id = #{userId} AND m.receiver_id = t.userId) OR (m.sender_id = t.userId AND m.receiver_id = #{userId}))\n" +
            "            AND m.send_time = t.maxTime\n" +
            "        JOIN user u ON u.user_id = t.userId\n" +
            "        ORDER BY m.send_time DESC")
    List<PrivateChatUserDTO> listPrivateChats(@Param("userId") Long userId);
    @Select("SELECT sender_id AS senderId, receiver_id AS receiverId,content,send_time AS sendTime  FROM message WHERE " +
            " (sender_id = #{senderId} AND receiver_id = #{receiverId}) " +
            " OR (sender_id = #{receiverId} AND receiver_id = #{senderId}) " +
            " ORDER BY send_time ASC")
    List<Message> getHistoryMessages(@Param("senderId") Long senderId,
                                     @Param("receiverId") Long receiverId);

    //删除聊天记录
    @Delete("DELETE FROM message WHERE sender_id = #{senderId} AND receiver_id = #{receiverId}")
    int deleteChatHistory(@Param("senderId") Long senderId, @Param("receiverId") Long receiverId);

}
